import {
	clearToken,
	getToken
} from "./AuthUtils";

const BASE_URL = "http://127.0.0.1/";


export function request(url = "", method = "GET", data = {}) {
	// 获取缓存的token
	const TOKEN = getToken();
	// 获取系统信息
	const systemInfo = uni.getSystemInfoSync();
	const {
		uniPlatform
	} = systemInfo;
	console.log(uniPlatform);
	// 解决微信小程序不需要代理的问题
	if (uniPlatform !== "web") {
		url = BASE_URL + url;
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			method,
			data,
			header: {
				Authorization: TOKEN
			}
		}).then(res => {
			if (res.data) {
				const {
					code
				} = res.data;
				if (code !== 20000) {
					// 50001-token过期，50002-非法token，50003-token不存在，50004-已在其他设备登录
					if ([50001, 50002, 50003].includes(code)) {
						// 清理token
						clearToken();
					}
					uni.showToast({
						title: res.data.message,
						icon: "none",
						position: "bottom"
					});
					reject(res.data);
				}
				resolve(res.data);
			}
		}).catch(err => {
			console.log(err);
			uni.hideLoading();
			uni.showModal({
				title: "网络异常",
				content: "当前网络异常，请刷新重试"
			})
		})
	})
}